new Vue({
    el: '#app',
    data: {
        userAvatarUrl: '',
        username: '',
        product: {
            productId: null,
            imageUrl: '',
            name: '',
            price: 0.00,
            averageRating: 0,
            totalReviews: 0,
            description: '',
            purchaseDate: '-'
        },
        reviewContent: '',
        orderId: null,
        // 所有评论
        allReviews: [],
        isAnonymous: 0, // 匿名评价，0不勾选，1勾选
        selectedRating: 0, // 用户选择的评分
        hoverRating: 0, // 鼠标悬停时的评分
        selectedImages: [], // 存储选中的图片文件
        imagePreviews: [], // 存储图片预览URL
        showImagePreviews: false // 控制图片预览区域的显示/隐藏
    },
    computed: {
        averageRating() {
            if (this.allReviews.length === 0) return 0;
            const total = this.allReviews.reduce((sum, comment) => sum + comment.grade, 0);
            return total / this.allReviews.length;
        },
    },
    methods: {
        //匿名用户头像
        getInitials(name) {
            if (!name) return '';
            const names = name.split(' ');
            let initials = names[0].substring(0, 1);
            if (names.length > 1) {
                initials += names[names.length - 1].substring(0, 1);
            }
            return initials;
        },
        // 获取商品详情
        fetchProductDetails() {
            const params = new URLSearchParams(window.location.search);
            this.orderId = params.get('orderId');
            this.productId = params.get('productId');

            if (this.productId) {
                $.ajax({
                    url: `http://localhost:8080/commodity/findCommodityById?id=${this.productId}`,
                    type: 'GET',
                    dataType: 'json',
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    success: (res) => {
                        if (res.code === 200 && res.data) {
                            const productData = res.data;
                            console.log('商品数据:', productData);
                            this.product = {
                                imageUrl: productData.imageUrl || '\\' + res.data.commodityPicture[0].commodityImageUrl.match(/photo[\\\\/].+$/)[0],
                                name: productData.commodityName,
                                price: productData.commoditySalePrice,
                                averageRating: productData.averageRating || 0,
                                totalReviews: productData.totalReviews || 0,
                                purchaseDate: ''
                            };
                        } else {
                            console.error('获取商品详情失败:', res.message);
                            alert('获取商品详情失败：' + (res.message || '未知错误'));
                        }
                    },
                    error: (xhr, status, error) => {
                        console.error(status, error);
                        alert('网络错误，获取商品详情失败');
                    }
                });
            } else {
                console.warn('URL中缺少productId参数，无法获取商品详情。');
            }
        },
        // 提交评论
        submitReview() {
            if (!this.reviewContent.trim()) {
                alert('评论内容不能为空！');
                return;
            }
            if (this.selectedRating === 0) {
                alert('请选择星级评分！');
                return;
            }

            const reviewTextData = {
                orderId: this.orderId,
                commodityId: this.productId,
                userId: localStorage.getItem('userId'),
                content: this.reviewContent,
                grade: this.selectedRating,
                isAnonymous: this.isAnonymous
            };

            console.log(reviewTextData);

            // 发送评论文本的AJAX请求
            $.ajax({
                url: `http://localhost:8080/comment/addComment?orderId=${this.orderId}&userId=` + localStorage.getItem('userId'),
                type: 'POST',
                contentType: 'application/json',
                headers: { 'token': localStorage.getItem('token') || '' },
                data: JSON.stringify(reviewTextData),
                success: (res) => {
                    if (res.code === 200) {
                        alert('评论提交成功！');
                        this.reviewContent = '';
                        this.selectedRating = 0; // 重置评分
                        this.isAnonymous = 0; // 重置匿名状态
                        // this.fetchAllReviews(); // 提交成功后刷新评论列表

                        // 如果有图片，则进行图片上传
                        if (this.selectedImages.length > 0) {
                            const commentId = res.data; // 假设后端返回 commentId
                            this.uploadImages(commentId); // 调用图片上传方法
                        } else {
                            // 如果没有图片，直接清空图片相关状态
                            this.selectedImages = [];
                            this.imagePreviews = [];
                            this.showImagePreviews = false;
                        }

                    } else {
                        console.log('评论提交失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，评论提交失败');
                    console.error('AJAX error submitting review text:', status, error);
                }
            });
        },
        // 图片上传方法
        uploadImages(commentId) {
            const formData = new FormData();
            formData.append('commentId', commentId); // 关联评论ID
            this.selectedImages.forEach((image) => {
                formData.append('images', image);
            });

            console.log('Uploading images for commentId:', commentId, formData);

            $.ajax({
                url: `http://localhost:8080/comment/addCommentImages?commentId=${commentId}`,
                type: 'POST',
                processData: false,
                contentType: false,
                headers: { 'token': localStorage.getItem('token') || '' },
                data: formData,
                success: (res) => {
                    if (res.code === 200) {
                        alert('图片上传成功！');
                        this.selectedImages = []; // 清空已选择的图片
                        this.imagePreviews = []; // 清空图片预览
                        this.showImagePreviews = false; // 隐藏预览区域
                    } else {
                        console.log('图片上传失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，图片上传失败');
                    console.error('AJAX error uploading images:', status, error);
                }
            });
        },
        // 获取所有评论
        fetchAllReviews() {
            if (!this.productId) {
                console.warn('缺少 productId，无法获取评论列表。');
                return;
            }

            $.ajax({
                url: `http://localhost:8080/comment/listComment?productId=${this.productId}`,
                type: 'GET',
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    console.log('获取评论成功:', res);
                    if (res.code === 200 && Array.isArray(res.data)) {
                        this.allReviews = res.data.map(review => ({
                            id: review.id,
                            isAnonymous: review.isAnonymous,
                            userId: review.userId,
                            username: review.isAnonymous == 0 ? review.user.userName : '匿名用户',
                            userAvatar:"http://localhost:8080" + review.user.avatar || ' ',    
                            reviewDate: review.commentTime || '未知日期',
                            content: review.content,
                            images: review.commentImages.map(item => (
                               'http://localhost:8080'+item.imageUrl
                            ))

                        }));
                        console.log(this.allReviews);
                        

                    } else {
                        console.error('获取评论列表失败:', res.message);
                        this.allReviews = [];
                    }
                },
                error: (xhr, status, error) => {
                    console.error(status, error);
                    this.allReviews = [];
                }
            });
        },
        // 设置评分
        setRating(rating) {
            this.selectedRating = rating;
        },
        // 鼠标悬停在星级上
        hoverStars(rating) {
            this.hoverRating = rating;
        },
        // 鼠标离开星级区域
        resetHover() {
            this.hoverRating = 0;
        },
        // 触发文件输入框点击
        triggerFileInput() {
            this.$refs.imageInput.click();
        },
        // 处理图片上传
        handleImageUpload(event) {
            const files = event.target.files;
            if (!files.length) {
                return;
            }

            const newImages = [];
            const newPreviews = [];
            const maxImages = 5;
            const currentImageCount = this.selectedImages.length;

            for (let i = 0; i < files.length; i++) {
                if (currentImageCount + newImages.length >= maxImages) {
                    alert(`最多只能上传 ${maxImages} 张图片。`);
                    break;
                }
                const file = files[i];
                if (!file.type.startsWith('image/')) {
                    alert('请选择图片文件。');
                    continue;
                }
                newImages.push(file);
                newPreviews.push(URL.createObjectURL(file));
            }
            this.selectedImages = [...this.selectedImages, ...newImages];
            this.imagePreviews = [...this.imagePreviews, ...newPreviews];
            this.showImagePreviews = true; // 选择图片后自动显示预览

            // 清空文件输入框，以便再次选择相同文件时也能触发change事件
            event.target.value = null;
        },
        // 移除选中的图片
        removeImage(index) {
            URL.revokeObjectURL(this.imagePreviews[index]); // 释放URL对象
            this.selectedImages.splice(index, 1);
            this.imagePreviews.splice(index, 1);
        }
    },
    created() {
        this.fetchProductDetails();
        this.fetchAllReviews(); // 页面加载时获取所有评论
        if (localStorage.getItem('userAvatarUrl')) {
            this.userAvatarUrl = localStorage.getItem('userAvatarUrl');
        }
        if (localStorage.getItem('username')) {
            this.username = localStorage.getItem('username');
        }
    }
}); 